package utils

import (
	"errors"
	"time"
)

const (
	FormatDatetime  = "2006-01-02 15:04:05"
	FormatDatetime1 = "20060102150405"
	FormatDatetime2 = "2006-01-02 15-04"    //%d-%02d-%02d %02d-%02d
	FormatDatetime3 = "2006_01_02_15_04_05" //YY_mm_dd_HH_MM_SS
	FormatDatetime4 = "2006-01-02 15-04-05" //%d-%02d-%02d %02d-%02d
	FormatDate      = "2006-01-02"
	FormatDate1     = "20060102"
)

type TimeRange struct {
	StartTime time.Time `json:"start_time"`
	EndTime   time.Time `json:"end_time"`
}

// PeriodsOverlap 判断两个时间段是否有重叠
func (r TimeRange) PeriodsOverlap(t TimeRange) bool {
	return periodsOverlap(r, t)
}

// Contains 判断一个时间是否在这个时间段内，包含临界时间
func (r TimeRange) Contains(t time.Time) bool {
	return r.StartTime.Equal(t) || r.EndTime.Equal(t) || (r.StartTime.Before(t) && r.EndTime.After(t))
}

// PeriodsOverlap 判断两个时间段是否有重叠
func PeriodsOverlap(st TimeRange, et TimeRange) bool {
	return periodsOverlap(st, et)
}

func periodsOverlap(st TimeRange, et TimeRange) bool {
	if et.StartTime.Before(st.EndTime) && st.StartTime.Before(et.EndTime) {
		return true
	}
	return false
}

func NewTimeRange(st time.Time, et time.Time) (TimeRange, error) {
	if !st.Before(et) {
		return TimeRange{}, errors.New("time range error")
	}
	return TimeRange{StartTime: st, EndTime: et}, nil
}

func NewTimeRangeFromString(st, et, layout string, loc *time.Location) (_ TimeRange, err error) {
	if loc == nil {
		loc = time.Local
	}
	var t1, t2 time.Time
	t1, err = time.ParseInLocation(layout, st, loc)
	if err != nil {
		return
	}
	t2, err = time.ParseInLocation(layout, et, loc)
	if err != nil {
		return
	}
	return NewTimeRange(t1, t2)
}
